{% extends "base.html" %}

{% block title %}包安装进度{% endblock %}

{% block content %}
<style>
.progress-log {
    background-color: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
    padding: 1rem;
    font-family: 'Courier New', monospace;
    font-size: 0.875rem;
    line-height: 1.4;
    max-height: 400px;
    overflow-y: auto;
}

.log-entry {
    margin-bottom: 0.25rem;
    padding: 0.125rem 0;
    word-wrap: break-word;
    white-space: pre-wrap;
}

.log-entry.text-error {
    color: #dc3545;
    font-weight: 500;
}

.log-entry.text-warning {
    color: #ffc107;
    font-weight: 500;
}

.log-entry.text-success {
    color: #198754;
    font-weight: 500;
}

.log-entry.text-info {
    color: #0dcaf0;
}

.progress-container {
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 0.5rem;
    padding: 1.5rem;
    margin-bottom: 2rem;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.progress-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.progress-title {
    margin: 0;
    color: #495057;
}

.progress-bar-container {
    margin-bottom: 1rem;
}

.progress-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.5rem;
}

.progress-text {
    font-weight: 500;
    color: #495057;
}

.progress-time {
    font-size: 0.875rem;
    color: #6c757d;
}

.task-item {
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 0.5rem;
    padding: 1rem;
    margin-bottom: 1rem;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.task-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 0.75rem;
}

.task-name {
    font-weight: 600;
    color: #495057;
    margin-bottom: 0.25rem;
}

.task-operation {
    font-size: 0.875rem;
    color: #6c757d;
}

.task-details {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
    font-size: 0.875rem;
}

.task-version {
    background: #e9ecef;
    padding: 0.25rem 0.5rem;
    border-radius: 0.25rem;
    color: #495057;
}

.task-duration {
    color: #6c757d;
}

.task-actions {
    display: flex;
    gap: 0.5rem;
}

.progress-status {
    padding: 0.25rem 0.75rem;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    font-weight: 500;
}

.status-running {
    background: #fff3cd;
    color: #856404;
}

.status-success {
    background: #d1e7dd;
    color: #0f5132;
}

.status-failed {
    background: #f8d7da;
    color: #721c24;
}

.status-cancelled {
    background: #e2e3e5;
    color: #383d41;
}

.no-tasks {
    text-align: center;
    padding: 3rem 1rem;
    color: #6c757d;
}

.no-tasks i {
    font-size: 3rem;
    margin-bottom: 1rem;
    opacity: 0.5;
}
</style>

<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0 text-gray-800">
            <i class="fas fa-tasks mr-2"></i>安装进度
        </h1>
        <div>
            <button class="btn btn-success mr-2" onclick="showQuickInstallModal()">
                <i class="fas fa-plus mr-1"></i>快速安装
            </button>
            <a href="{{ url_for('package_management') }}" class="btn btn-secondary mr-2">
                <i class="fas fa-arrow-left mr-1"></i>返回包管理
            </a>
            <!-- 后台安装功能已移除 -->
            <button class="btn btn-primary" onclick="refreshProgress()">
                <i class="fas fa-sync-alt mr-1"></i>刷新
            </button>
        </div>
    </div>

    <!-- 前台安装进度 -->
    <div id="foregroundProgress" style="display: none;">
        <div class="progress-container">
            <div class="progress-header">
                <h5 class="progress-title">
                    <i class="fas fa-download mr-2"></i>
                    <span id="foregroundTitle">前台安装进度</span>
                </h5>
                <span class="progress-status status-running" id="foregroundStatus">运行中</span>
            </div>
            <div class="progress-bar-container">
                <div class="progress-info">
                    <span class="progress-text" id="foregroundProgressText">正在安装...</span>
                    <span class="progress-time" id="foregroundTime">00:00</span>
                </div>
                <div class="progress">
                    <div class="progress-bar progress-bar-striped progress-bar-animated" 
                         role="progressbar" style="width: 0%" id="foregroundProgressBar"></div>
                </div>
            </div>
            <div class="progress-log custom-pre" id="foregroundLog" style="max-height: 400px; overflow-y: auto;">
            </div>
        </div>
    </div>

    <!-- 后台任务列表 -->
    <div class="task-list">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="mb-0">
                <i class="fas fa-server mr-2"></i>后台任务
            </h5>
            {% if current_user.is_administrator() %}
            <button id="cleanupOrphanedTasksBtn" class="btn btn-sm btn-outline-warning" title="清理孤立任务">
                <i class="fas fa-broom"></i> 清理孤立任务
            </button>
            {% endif %}
        </div>
        <div id="backgroundTasks">
            <div class="no-tasks">
                <i class="fas fa-clock"></i>
                <p>暂无后台任务</p>
            </div>
        </div>
    </div>
</div>

<!-- 快速安装模态框 -->
<div class="modal fade" id="quickInstallModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">快速安装包</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="quickInstallForm">
                    <div class="mb-3">
                        <label for="quickPackageName" class="form-label">包名</label>
                        <input type="text" class="form-control" id="quickPackageName" placeholder="例如: requests" required>
                    </div>
                    <div class="mb-3">
                        <label for="quickVersion" class="form-label">版本（可选）</label>
                        <input type="text" class="form-control" id="quickVersion" placeholder="例如: 2.28.1">
                    </div>
                    <div class="mb-3">
                        <label for="quickMirrorSource" class="form-label">镜像源</label>
                        <select class="form-control" id="quickMirrorSource">
                            <option value="官方源">官方源</option>
                            <option value="清华大学">清华</option>
                            <option value="阿里云">阿里云</option>
                            <option value="中国科技大学">中科大</option>
                            <option value="豆瓣">豆瓣</option>
                            <option value="华为云">华为云</option>
                            <option value="腾讯云">腾讯云</option>
                        </select>
                    </div>
                    <!-- 后台安装功能已移除 -->
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitQuickInstall()">开始安装</button>
            </div>
        </div>
    </div>
</div>

<!-- 任务详情模态框 -->
<div class="modal fade" id="taskDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">任务详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="taskDetailContent"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 全局变量
let progressPollingInterval = null;
let backgroundTaskPollingInterval = null;
let progressStartTime = null;

// 页面加载完成后初始化
$(document).ready(function() {
    // 检查是否有前台安装进度
    checkForegroundProgress();
    
    // 加载后台任务
    loadBackgroundTasks();
    
    // 开始后台任务轮询
    startBackgroundTaskPolling();
});

// 检查前台安装进度
function checkForegroundProgress() {
    $.ajax({
        url: '{{ url_for("get_progress") }}',
        method: 'GET',
        success: function(response) {
            if (response.success && response.progress && response.progress.status === 'running') {
                showForegroundProgress();
                startProgressPolling();
            } else {
                hideForegroundProgress();
            }
        },
        error: function() {
            hideForegroundProgress();
        }
    });
}

// 显示前台进度
function showForegroundProgress() {
    $('#foregroundProgress').show();
    progressStartTime = new Date();
}

// 隐藏前台进度
function hideForegroundProgress() {
    $('#foregroundProgress').hide();
    stopProgressPolling();
}

// 开始进度轮询
function startProgressPolling() {
    if (progressPollingInterval) {
        clearInterval(progressPollingInterval);
    }
    
    progressPollingInterval = setInterval(function() {
        $.ajax({
            url: '{{ url_for("get_progress") }}',
            method: 'GET',
            success: function(response) {
                if (response.success && response.progress) {
                    updateForegroundProgress(response.progress);
                    
                    if (response.progress.status !== 'running') {
                        stopProgressPolling();
                        setTimeout(function() {
                            hideForegroundProgress();
                            loadBackgroundTasks();
                        }, 3000);
                    }
                }
            },
            error: function() {
                console.log('获取进度失败');
            }
        });
    }, 1000);
}

// 停止进度轮询
function stopProgressPolling() {
    if (progressPollingInterval) {
        clearInterval(progressPollingInterval);
        progressPollingInterval = null;
    }
}

// 更新前台进度
function updateForegroundProgress(progress) {
    // 更新状态
    $('#foregroundStatus').text(progress.status === 'running' ? '运行中' : 
                               progress.status === 'success' ? '成功' : '失败')
                         .removeClass('status-running status-success status-failed')
                         .addClass('status-' + progress.status);
    
    // 更新进度条 - 根据消息数量计算进度
    const messageCount = progress.progress_messages ? progress.progress_messages.length : 0;
    const progressPercent = Math.min(messageCount * 5, 90); // 每条消息5%，最多90%
    $('#foregroundProgressBar').css('width', progressPercent + '%');
    
    // 更新进度文本 - 显示包名和操作
    const packageName = progress.package_name || '未知包';
    const operation = progress.operation === 'install' ? '安装' : 
                     progress.operation === 'upgrade' ? '升级' : 
                     progress.operation === 'uninstall' ? '卸载' : '操作';
    $('#foregroundProgressText').text(`正在${operation} ${packageName}...`);
    
    // 更新标题
    $('#foregroundTitle').text(`${operation} ${packageName}`);
    
    // 更新运行时间
    if (progress.elapsed_time) {
        const elapsed = Math.floor(progress.elapsed_time);
        const minutes = Math.floor(elapsed / 60);
        const seconds = elapsed % 60;
        $('#foregroundTime').text(
            (minutes < 10 ? '0' : '') + minutes + ':' + 
            (seconds < 10 ? '0' : '') + seconds
        );
    }
    
    // 更新日志
    if (progress.progress_messages && progress.progress_messages.length > 0) {
        let logHtml = '';
        progress.progress_messages.forEach(function(msg) {
            const timestamp = new Date(msg.timestamp * 1000).toLocaleTimeString();
            const levelClass = msg.level === 'error' ? 'text-error' : 
                             msg.level === 'warning' ? 'text-warning' : 
                             msg.level === 'success' ? 'text-success' : 'text-info';
            logHtml += `<div class="log-entry ${levelClass}" style="margin-bottom: 0.25rem; padding: 0.125rem 0;">[${timestamp}] ${msg.message}</div>`;
        });
        $('#foregroundLog').html(logHtml);
        $('#foregroundLog').scrollTop($('#foregroundLog')[0].scrollHeight);
    }
}

// 加载后台任务
function loadBackgroundTasks() {
    $.ajax({
        url: '{{ url_for("get_background_tasks") }}',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                updateBackgroundTasks(response.tasks);
            } else {
                console.log('获取后台任务失败:', response.message);
            }
        },
        error: function() {
            console.log('获取后台任务失败');
        }
    });
}

// 更新后台任务列表
function updateBackgroundTasks(tasks) {
    const container = $('#backgroundTasks');
    
    if (!tasks || tasks.length === 0) {
        container.html(`
            <div class="no-tasks">
                <i class="fas fa-clock"></i>
                <p>暂无后台任务</p>
            </div>
        `);
        return;
    }
    
    let html = '';
    tasks.forEach(function(task) {
        const statusClass = 'status-' + task.status;
        const statusText = {
            'running': '运行中',
            'success': '成功',
            'failed': '失败',
            'cancelled': '已取消'
        }[task.status] || task.status;
        
        const operationText = {
            'install': '安装',
            'upgrade': '升级',
            'uninstall': '卸载'
        }[task.operation] || task.operation;
        
        const duration = task.duration ? formatDuration(task.duration) : 
                        task.elapsed_time ? formatDuration(task.elapsed_time) : '';
        
        html += `
            <div class="task-item">
                <div class="task-header">
                    <div>
                        <div class="task-name">${task.package_name}</div>
                        <div class="task-operation">${operationText}</div>
                    </div>
                    <span class="progress-status ${statusClass}">${statusText}</span>
                </div>
                <div class="task-details">
                    <div>
                        ${task.version ? `<span class="task-version">版本: ${task.version}</span>` : ''}
                    </div>
                    <div>
                        <span class="task-duration">${duration}</span>
                    </div>
                </div>
                <div class="task-actions">
                    <button class="btn btn-sm btn-outline-primary" onclick="viewTaskDetail(${task.id})" title="查看任务详情">
                        <i class="fas fa-eye"></i> 详情
                    </button>
                    ${task.status === 'running' ? `
                        <button class="btn btn-sm btn-outline-danger" onclick="cancelTask(${task.id})" title="取消任务">
                            <i class="fas fa-stop"></i> 取消
                        </button>
                    ` : ''}
                    ${task.status === 'failed' ? `
                        <button class="btn btn-sm btn-outline-warning" onclick="retryTask(${task.id})" title="重试任务">
                            <i class="fas fa-redo"></i> 重试
                        </button>
                    ` : ''}
                </div>
            </div>
        `;
    });
    
    container.html(html);
}

// 格式化持续时间
function formatDuration(seconds) {
    if (!seconds) return '';
    
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);
    
    if (hours > 0) {
        return `${hours}时${minutes}分${secs}秒`;
    } else if (minutes > 0) {
        return `${minutes}分${secs}秒`;
    } else {
        return `${secs}秒`;
    }
}

// 查看任务详情
function viewTaskDetail(taskId) {
    $.ajax({
        url: `/background_task/${taskId}`,
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const task = response.task;
                let content = `
                    <div class="mb-3">
                        <h6>任务信息</h6>
                        <table class="table table-sm">
                            <tr><td>包名:</td><td>${task.package_name}</td></tr>
                            <tr><td>操作:</td><td>${task.operation}</td></tr>
                            <tr><td>版本:</td><td>${task.version || '最新版本'}</td></tr>
                            <tr><td>状态:</td><td><span class="progress-status status-${task.status}">${task.status}</span></td></tr>
                            <tr><td>开始时间:</td><td>${task.start_time || ''}</td></tr>
                            <tr><td>结束时间:</td><td>${task.end_time || ''}</td></tr>
                            <tr><td>运行时间:</td><td>${formatDuration(task.duration || task.elapsed_time)}</td></tr>
                        </table>
                    </div>
                `;
                
                if (task.progress_messages && task.progress_messages.length > 0) {
                    content += `
                        <div class="mb-3">
                            <h6>进度日志 (${task.progress_messages.length} 条)</h6>
                            <div class="progress-log custom-pre" style="max-height: 400px; overflow-y: auto;">
                    `;
                    task.progress_messages.forEach(function(msg) {
                        const level = msg.level || 'info';
                        const timestamp = msg.timestamp ? new Date(msg.timestamp * 1000).toLocaleTimeString() : '';
                        const levelClass = level === 'error' ? 'text-error' : 
                                         level === 'warning' ? 'text-warning' : 
                                         level === 'success' ? 'text-success' : 'text-info';
                        content += `<div class="log-entry ${levelClass}">[${timestamp}] ${msg.message}</div>`;
                    });
                    content += `</div></div>`;
                }
                
                if (task.output) {
                    content += `
                        <div class="mb-3">
                            <h6>输出信息</h6>
                            <pre class="bg-light p-3 rounded"><code>${task.output}</code></pre>
                        </div>
                    `;
                }
                
                if (task.error_message) {
                    content += `
                        <div class="mb-3">
                            <h6>错误信息</h6>
                            <div class="alert alert-danger">${task.error_message}</div>
                        </div>
                    `;
                }
                
                $('#taskDetailContent').html(content);
                
                // 显示模态框
                if (typeof bootstrap !== 'undefined') {
                    const modal = new bootstrap.Modal(document.getElementById('taskDetailModal'));
                    modal.show();
                } else {
                    $('#taskDetailModal').modal('show');
                }
            } else {
                alert('获取任务详情失败: ' + response.message);
            }
        },
        error: function() {
            alert('获取任务详情失败');
        }
    });
}

// 取消任务
function cancelTask(taskId) {
    if (!confirm('确定要取消这个任务吗？')) {
        return;
    }
    
    $.ajax({
        url: `/background_task/${taskId}/cancel`,
        method: 'POST',
        success: function(response) {
            if (response.success) {
                alert('任务已取消');
                loadBackgroundTasks();
            } else {
                alert('取消任务失败: ' + response.message);
            }
        },
        error: function() {
            alert('取消任务失败');
        }
    });
}

// 重试任务
function retryTask(taskId) {
    if (!confirm('确定要重试这个任务吗？')) {
        return;
    }
    
    $.ajax({
        url: `/background_task/${taskId}/retry`,
        method: 'POST',
        success: function(response) {
            if (response.success) {
                alert('任务已开始重试');
                loadBackgroundTasks();
            } else {
                alert('重试任务失败: ' + response.message);
            }
        },
        error: function() {
            alert('重试任务失败');
        }
    });
}

// 开始后台任务轮询
function startBackgroundTaskPolling() {
    if (backgroundTaskPollingInterval) {
        clearInterval(backgroundTaskPollingInterval);
    }
    
    backgroundTaskPollingInterval = setInterval(function() {
        loadBackgroundTasks();
    }, 5000); // 每5秒刷新一次
}

// 停止后台任务轮询
function stopBackgroundTaskPolling() {
    if (backgroundTaskPollingInterval) {
        clearInterval(backgroundTaskPollingInterval);
        backgroundTaskPollingInterval = null;
    }
}

// 刷新进度
function refreshProgress() {
    checkForegroundProgress();
    loadBackgroundTasks();
}

// 显示快速安装模态框
function showQuickInstallModal() {
    // 加载当前镜像源
    loadCurrentMirror();
    
    // 显示模态框
    if (typeof bootstrap !== 'undefined') {
        const modal = new bootstrap.Modal(document.getElementById('quickInstallModal'));
        modal.show();
    } else {
        $('#quickInstallModal').modal('show');
    }
}

// 加载当前镜像源
function loadCurrentMirror() {
    $.ajax({
        url: '{{ url_for("get_mirrors") }}',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const currentMirror = response.current_mirror;
                const mirrors = response.mirrors;
                
                // 找到对应的镜像源名称
                for (const [name, url] of Object.entries(mirrors)) {
                    if (url === currentMirror) {
                        $('#quickMirrorSource').val(name);
                        break;
                    }
                }
            }
        },
        error: function() {
            console.log('获取镜像源信息失败');
        }
    });
}

// 提交快速安装
function submitQuickInstall() {
    const packageName = $('#quickPackageName').val().trim();
    const version = $('#quickVersion').val().trim();
    const mirrorSource = $('#quickMirrorSource').val();
    
    if (!packageName) {
        alert('请输入包名');
        return;
    }
    
    // 先设置镜像源
    $.ajax({
        url: '{{ url_for("set_mirror") }}',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            mirror_name: mirrorSource
        }),
        success: function(mirrorResponse) {
            if (mirrorResponse.success) {
                // 然后安装包
                $.ajax({
                    url: '{{ url_for("install_package") }}',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        package_name: packageName,
                        version: version || null
                    }),
                    success: function(response) {
                        if (response.success) {
                            // 关闭模态框
                            if (typeof bootstrap !== 'undefined') {
                                const modal = bootstrap.Modal.getInstance(document.getElementById('quickInstallModal'));
                                modal.hide();
                            } else {
                                $('#quickInstallModal').modal('hide');
                            }
                            
                            // 重置表单
                            $('#quickInstallForm')[0].reset();
                            
                            // 显示成功消息
                            alert(response.message);
                            
                            // 刷新后台任务列表
                            loadBackgroundTasks();
                        } else {
                            alert('安装失败: ' + response.message);
                        }
                    },
                    error: function() {
                        alert('安装失败，请重试');
                    }
                });
            } else {
                alert('设置镜像源失败: ' + mirrorResponse.message);
            }
        },
        error: function() {
            alert('设置镜像源失败，请重试');
        }
    });
}

// 清理孤立任务
function cleanupOrphanedTasks() {
    if (!confirm('确定要清理孤立任务吗？这将清理数据库中状态为运行中但实际已不存在的任务。')) {
        return;
    }
    
    $.ajax({
        url: '{{ url_for("cleanup_orphaned_tasks_route") }}',
        method: 'POST',
        success: function(response) {
            if (response.success) {
                alert('孤立任务清理完成');
                loadBackgroundTasks();
            } else {
                alert('清理孤立任务失败: ' + response.message);
            }
        },
        error: function() {
            alert('清理孤立任务失败，请重试');
        }
    });
}

// 页面卸载时清理
$(window).on('beforeunload', function() {
    stopProgressPolling();
    stopBackgroundTaskPolling();
});

// 绑定清理孤立任务按钮事件
$(document).ready(function() {
    $('#cleanupOrphanedTasksBtn').on('click', cleanupOrphanedTasks);
});
</script>
{% endblock %}